<template>
  <a-modal
    :title="this.title"
    width=50rem
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="()=>{this.visible=false}"
  >
    <a-spin :spinning="confirmLoading">
      <a-form-model
        ref="form"
        :model="entity"
        :rules="rules"
        v-bind="layout"
      >
      <a-form-model-item
        label="软件"
        prop="id"
      >
        <a-select
          v-model="entity.id"
          @select="select"
          allowClear
          showSearch
        >
          <a-select-option 
            v-for="item in softListEx"
            :key="item.id"
          >{{item.name}}</a-select-option>
        </a-select>
      </a-form-model-item>
       <!-- <a-form-model-item
          label="类型"
          prop="type"
        >
          <a-select
            v-model="entity.type"
            @select="select"
          >
            <a-select-option :key="1">期限</a-select-option>
            <a-select-option :key="2">余额</a-select-option>
          </a-select>
        </a-form-model-item> -->
        <a-form-model-item
          label="策略"
          prop="strategyId"
        >
          <a-select
            v-model="entity.strategyId"
            allowClear
            showSearch
            :filterOption="filterOption"
          >
            <a-select-option
              v-for="item in strategyListEx"
              :key="item.id"
            >{{item.name}}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item
          label="卡密前缀"
          prop="prefix"
        >
          <a-input v-model="entity.prefix" />
        </a-form-model-item>
        <a-form-model-item
          label="张数"
          prop="count"
        >
          <a-input-number
            v-model="entity.count"
            :min="0"
          />
        </a-form-model-item>
      </a-form-model>
    </a-spin>
  </a-modal>
</template>

<script>
import { forEach } from 'core-js/library/fn/dict'
export default {
  props: {
    afterSubmit: {
      type: Function,
      default: null
    },
    /**行为，1新增，2更新 */
    behaviorType:{
      type:Number,
      default: 1
    }
  },
  data() {
    return {
      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 18 }
      },
      visible: false,
      confirmLoading: false,
      entity: {},
      rules: {
        strategyId: [{ required: true, message: '必填' }],
        count: [{ required: true, message: '必填' }],
        id: [{ required: true, message: '必填' }]
      },
      strategyListEx:[],  // 初始化了，才能实时取到最新的。
      title:"生成卡密",
      softId:null
    }
  },
  mounted(){
    this.getMySoftListEx()
  },
  methods: {
    init() {
      this.visible = true
      this.entity = {}
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    },
    openForm(title) {
      this.init()
      if(title){
        this.title = title
      }
    },
    handleSubmit() {
      this.$refs['form'].validate(valid => {
        if (!valid) {
          return
        }
        let url = "/myauth/web/addMyCard"
        this.confirmLoading = true
        if(url){
          this.$http.post(url, this.entity).then(resJson => {
            this.confirmLoading = false
            if (resJson.success) {
              this.$message.success(resJson.msg+"，复制成功！")
              this.afterSubmit()
              this.copyToClipboard(resJson.result.ckeyStr)
              this.visible = false
            } else {
              this.$message.error(resJson.msg)
            }
          })
        }
      })
    },
    copyToClipboard(textToCopy) {
      try{
        // navigator clipboard 需要https等安全上下文
        if (navigator.clipboard && window.isSecureContext) {
          // navigator clipboard 向剪贴板写文本
          navigator.clipboard.writeText(textToCopy)
            .then(() => {
              this.$message.success("复制成功")
            })
            .catch(err => {
                this.$message.error(err)
            });
        } else {
          // 创建text area
          let textArea = document.createElement("textarea");
          textArea.value = textToCopy;
          // 使text area不在viewport，同时设置不可见
          textArea.style.position = "absolute";
          textArea.style.opacity = 0;
          textArea.style.left = "-999999px";
          textArea.style.top = "-999999px";
          document.body.appendChild(textArea);
          textArea.focus();
          textArea.select();
          return new Promise((res, rej) => {
            // 执行复制命令并移除文本框
            document.execCommand('copy') ? res() : rej();
            textArea.remove();
            this.$message.success("复制成功")
          });
        }
      }
      catch{
        this.$message.error("复制失败")
      }
    },
    getStrategyListEx(softId) {
      var userInfo = JSON.parse(localStorage.getItem('userInfo'))
      var tag = userInfo.roleName.charAt(0)
      this.$http.post('/myauth/web/getStrategyListEx', { fromSoftId: softId}).then(resJson => {
        if(resJson.success){
          var tempList = resJson.result
          var resultList = []
          tempList.forEach(function(temp){
            if(tag == 'T'){
              if(temp.name.charAt(0) == 'T'){
                resultList.push({name:temp.name, id:temp.id})
              }
            }else{
              if(temp.name.charAt(0) != 'T'){
                resultList.push({name:temp.name, id:temp.id})
              }
            }
          })
          this.strategyListEx = resultList
        }
        else{
          this.$message.error(resJson.msg)
          console.error(resJson)
        }
      })
    },
    getMySoftListEx(){
      this.$http.post('/myauth/web/getMySoftListEx').then(resJson => {
        if(resJson.success){
          this.softListEx = resJson.result
        }
        else{
          this.$message.error(resJson.msg)
          console.error(resJson)
        }
      })
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
    select(value){
      this.getStrategyListEx(value)
    }
  }
}
</script>
